package com.exam.stu.power.business;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.exam.base.business.AbstractBusiness;
import com.exam.base.model.ResponsePageModel;
import com.exam.base.service.IAbstractService;
import com.exam.base.util.ServletBeanTools; 
import com.exam.stu.power.model.TbBtn;
import com.exam.stu.power.model.TbMenu;
import com.exam.stu.power.model.vo.ZkTreeNode; 
import com.exam.stu.power.service.TbBtnService;
import com.exam.stu.power.service.TbMenuService;
import com.exam.stu.role.model.TbRoleMenu;
import com.exam.stu.role.model.TbUserRole;
import com.exam.stu.role.service.TbRoleMenuService;
import com.exam.stu.role.service.TbUserRoleService;
import com.exam.stu.user.model.TbUser;

/**
 * 权限业务
 * @author Administrator
 *
 */
@Service("powerBusiness")
public class PowerBusiness extends AbstractBusiness<TbMenu>{
	
	@Autowired
	private TbMenuService tbMenuService;
	
	@Autowired
	private PowerMenuBtnBusiness powerMenuBtnBusiness;
	
	@Autowired
	private TbUserRoleService tbUserRoleService;
	
	@Autowired
	private TbRoleMenuService tbRoleMenuService;
	
	@Autowired
	private TbBtnService tbBtnService;
	
	/**
	 * 获取菜单树结构数据
	 * @return
	 */
	public String getMenuJsonData()
	{
		TbMenu queryModel = new TbMenu();
		List<TbMenu> lstMenu = tbMenuService.queryList(queryModel);
		
		ZkTreeNode rootTreeNode = new ZkTreeNode();
		
	    TbMenu rootMenu = null;
		
		for (TbMenu tbMenu : lstMenu) {
			if (StringUtils.isEmpty(tbMenu.getParentId()))
			{
				rootMenu = tbMenu;
				break;
			}
		}
		rootTreeNode.setChildren(new ArrayList<ZkTreeNode>());
		rootTreeNode.setId(rootMenu.getId());
		rootTreeNode.setText(rootMenu.getMenuName());
		rootTreeNode.setCode(rootMenu.getMenuCode());
		
		generateTree(rootMenu,rootTreeNode,lstMenu);
		
		List<ZkTreeNode> lstNode = new ArrayList<ZkTreeNode>();
		lstNode.add(rootTreeNode);
		return JSONArray.toJSONString(lstNode); 
	}
	
	/**
	 * 构建树
	 * @param rootMenu
	 * @param treeNode
	 * @param lstMenu
	 */
	private void generateTree (TbMenu rootMenu,ZkTreeNode treeNode,List<TbMenu> lstMenu)
	{
		for (TbMenu tbMenu : lstMenu) {
			if (StringUtils.isEmpty(tbMenu.getParentId()))
			{
				continue;
			}
			if (tbMenu.getParentId().equals(rootMenu.getId()))
			{
				ZkTreeNode childTreeNode = new ZkTreeNode();
				childTreeNode.setChildren(new ArrayList<ZkTreeNode>());
				childTreeNode.setId(tbMenu.getId());
				childTreeNode.setCode(tbMenu.getMenuCode());
				childTreeNode.setText(tbMenu.getMenuName()); 
				treeNode.getChildren().add(childTreeNode); 
				generateTree(tbMenu,childTreeNode,lstMenu);
				continue;
			}
		}
	}
	
	/**
	 * 获取分页菜单数据
	 * @param request
	 * @return
	 */
	public ResponsePageModel<TbMenu> getMenuPageData (HttpServletRequest request)
	{
		try {
			
            TbMenu queryModel = ServletBeanTools.populate(TbMenu.class, request);  
            queryModel.setSortName("show_Order");
			return this.getPageData(queryModel);
			
		} catch (Exception e) { 
			e.printStackTrace();
		}
		
		return null;
	}

	/**
	 * 菜单按钮加载
	 * @param request
	 * @return
	 */
	public ResponsePageModel<TbBtn> getMenuBtnPageData(
			HttpServletRequest request) {
		try {

			TbBtn queryModel = ServletBeanTools.populate(TbBtn.class, request);
			return powerMenuBtnBusiness.getPageData(queryModel);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/**
	 * 添加菜单
	 * @param addMenu
	 * @throws Exception 
	 */
	public void addMenu(TbMenu addMenu) throws Exception
	{
		TbMenu queryMenu = new TbMenu();
		queryMenu.setMenuCode(addMenu.getMenuCode());
		
		int count = getBaseService().queryCount(queryMenu);
		
		if (count > 0)
		{
			throw new Exception("菜单编码重复！");
		}
		
		getBaseService().add(addMenu);
	}
 
	/**
	 * 删除菜单
	 * @param menuId
	 */
	public void deleteMenu(String menuId)
	{
		tbMenuService.deleteBtnAuth(menuId);
		tbMenuService.deleteAuth(menuId);
		tbMenuService.deleteBtn(menuId);
		tbMenuService.delete(menuId);
	}
	
	@Override
	protected IAbstractService<TbMenu> getBaseService() {
		return tbMenuService;
	}

	/**
	 * 更新按钮
	 * @param queryModel
	 * @throws Exception 
	 */
	public void updateMenu(TbMenu upMenu) throws Exception {
		 
		TbMenu queryMenu = new TbMenu();
		queryMenu.setMenuCode(upMenu.getMenuCode());
		
		List<TbMenu> lstMenu = getBaseService().queryList(queryMenu);
		
		for (TbMenu tbMenu : lstMenu) {
			if (!tbMenu.getId().equals(upMenu.getId()))
			{
				throw new Exception("菜单编码重复！");
			}
		}
		 
		getBaseService().update(upMenu);
		
	}
	
	/**
	 * 构建菜单
	 * @param userId
	 * @return
	 */
	public List<TbMenu> getUserMenu(String userId)
	{
		TbUserRole uerRole = new TbUserRole();
		uerRole.setUserId(userId);
		List<TbUserRole> lstRoleData = tbUserRoleService.queryList(uerRole);
		
		if (lstRoleData.size() <= 0)
		{
			return null;
		}
		
		List<String> lstRoleId = new ArrayList<String>();
		
		for (TbUserRole userRole : lstRoleData) {
			lstRoleId.add(userRole.getRoleId());
		}
		
		TbRoleMenu queryMenu = new TbRoleMenu(); 
		queryMenu.setLstRoleId(lstRoleId);
		List<TbRoleMenu> lstRoleMenu = tbRoleMenuService.queryList(queryMenu);
		
		if (lstRoleMenu.size() <= 0 )
		{
			return null;
		}
		
		Set<String> menuSet = new HashSet<String>();
		Map<String,HashSet<String>> menuBtnMap = new HashMap<String, HashSet<String>>();
		List<TbBtn> lstBtn = tbBtnService.queryList(new TbBtn());
		Map<String,TbBtn> btnMap = new HashMap<String, TbBtn>();
		for (TbBtn tbBtn : lstBtn) {
			btnMap.put(tbBtn.getId(), tbBtn);
		}
		
		for (TbRoleMenu roleMenu : lstRoleMenu) {
			menuSet.add(roleMenu.getMenuId());
			if (StringUtils.isEmpty(roleMenu.getBtnId()))
			{
				continue;
			}
			if (!menuBtnMap.containsKey(roleMenu.getMenuId()))
			{
				menuBtnMap.put(roleMenu.getMenuId(), new HashSet<String>());
			}
			String[] btnArray = roleMenu.getBtnId().split(",");
			
			for (String btnId : btnArray) {
				menuBtnMap.get(roleMenu.getMenuId()).add(btnId);
				menuSet.add(btnMap.get(btnId).getMenuId());
			} 
		}
		
		// 获取所有的菜单  按钮
		
		List<TbMenu> lstMenu = tbMenuService.findByIds(menuSet.toArray(new String[menuSet.size()]));
 
		for (TbMenu tbMenu : lstMenu) {
			menuSet.add(tbMenu.getParentId());
		} 
		TbMenu rootMenu = tbMenuService.getRootMenu();
		menuSet.remove(rootMenu.getId());
		lstMenu = tbMenuService.findByIds(menuSet.toArray(new String[menuSet.size()]));
		 
		
		
		List<TbMenu> lstMenuData = new ArrayList<TbMenu>();
		
		for (TbMenu tbMenu : lstMenu) {
			if (!tbMenu.getParentId().equals(rootMenu.getId()))
			{
				continue;
			}
			// 子菜单
			lstMenuData.add(tbMenu);
			generateMenu(lstMenuData,tbMenu,lstMenu,menuBtnMap,btnMap);
			// 按钮
			if (!menuBtnMap.containsKey(tbMenu.getId()))
			{
				continue;
			}
			tbMenu.setLstBtn(new ArrayList<TbBtn>());
			for (String btnId : menuBtnMap.get(tbMenu.getId())) {
				tbMenu.getLstBtn().add(btnMap.get(btnId));
			}
		} 
		return lstMenuData;
	}
	
	/**
	 * 递归构建菜单
	 * @param lstData
	 * @param rootMenu
	 * @param lstMenu
	 * @param menuBtnMap
	 * @param btnMap
	 */
	public void generateMenu(List<TbMenu> lstData, TbMenu rootMenu,
			List<TbMenu> lstMenu, Map<String, HashSet<String>> menuBtnMap,
			Map<String, TbBtn> btnMap) {
		for (TbMenu tbMenu : lstMenu) {
			if (!tbMenu.getParentId().equals(rootMenu.getId())) {
				continue;
			}
			lstData.add(tbMenu);
			generateMenu(lstData,tbMenu,lstMenu,menuBtnMap,btnMap);
			// 按钮
			if (!menuBtnMap.containsKey(tbMenu.getId())) {
				continue;
			}
			tbMenu.setLstBtn(new ArrayList<TbBtn>());
			for (String btnId : menuBtnMap.get(tbMenu.getId())) {
				tbMenu.getLstBtn().add(btnMap.get(btnId));
			}
		}
	}

	public TbMenu getRootMenu() { 
		return tbMenuService.getRootMenu();
	}

	 
}
